<template>
  <div style="width:90%;">
    <el-button @click="goback()" size="mini" type="primary" style="margin-left:800px">返回</el-button>
    <el-form :model="couponForm" :rules="rules" ref="couponForm" label-width="150px">
      <el-input v-model="couponForm.uuid" type="hidden"></el-input>
      <el-form-item label="卡券名称：" prop="couponName">
        <el-input
          v-model="couponForm.couponName"
          :disabled="disabledFlag"
          style="width:360px;"
          placeholder="请输入卡券名称"
          maxlength="30"
          show-word-limit
        ></el-input>
      </el-form-item>
      <!--
      <el-form-item label="卡券编号：" prop="couponNo">
        <el-input v-model="couponForm.couponNo" :disabled="disabledFlag"></el-input>
      </el-form-item>
      -->
      <el-form-item label="卡券图片：" prop="couponPicture">
        <el-radio-group v-model="couponForm.couponPicture" :disabled="disabledFlag">
          <el-radio-button label="3">
            <img src="../../assets/images/coupon/couponBg3.png" style="width:80px;padding:0px;" />
          </el-radio-button>
          <el-radio-button label="2">
            <img src="../../assets/images/coupon/couponBg2.png" style="width:80px;" />
          </el-radio-button>
          <el-radio-button label="1">
            <img src="../../assets/images/coupon/couponBg1.png" style="width:80px;" />
          </el-radio-button>
        </el-radio-group>
      </el-form-item>
      <el-form-item label="卡券类型：" prop="couponType">
        <el-radio-group v-model="couponForm.couponType" :disabled="disabledFlag">
          <el-radio-button label="1">现金券</el-radio-button>
          <el-radio-button label="2">满减券</el-radio-button>
          <el-radio-button label="3">折扣券</el-radio-button>
        </el-radio-group>
      </el-form-item>
      <el-form-item label="卡券使用条件：" prop="conponLimitMoney">
        <el-input
          v-model="couponForm.conponLimitMoney"
          :disabled="disabledFlag"
          style="width:360px;"
          @blur="numberBlur($event,'卡券使用条件')"
          placeholder="请输入使用卡券的最低金额"
        ></el-input>
      </el-form-item>
      <el-form-item label="卡券面值：" prop="couponMoney" v-if="couponForm.couponType != '3'">
        <el-input
          v-model="couponForm.couponMoney"
          :disabled="disabledFlag"
          style="width:360px;"
          @blur="numberBlur($event,'卡券面值')"
          placeholder="请输入卡券的面值"
        ></el-input>
      </el-form-item>
      <el-form-item label="卡券折扣：" prop="couponDiscount" v-if="couponForm.couponType == '3'">
        <el-input
          v-model="couponForm.couponDiscount"
          :disabled="disabledFlag"
          style="width:360px;"
          @blur="discountBlur($event,'卡券折扣')"
          placeholder="请输入0-1以内的小数"
        ></el-input>
      </el-form-item>
      <el-form-item label="有效期类型：" prop="validType">
        <el-radio-group v-model="couponForm.validType" :disabled="disabledFlag">
          <el-radio-button label="1">有效天数</el-radio-button>
          <el-radio-button label="2">有效日期</el-radio-button>
        </el-radio-group>
      </el-form-item>
      <el-form-item label="有效天数：" prop="validDate" v-if="couponForm.validType == '1'">
        <el-input
          v-model="couponForm.validDate"
          :disabled="disabledFlag"
          style="width:360px;"
          @blur="numberBlur($event,'有效天数')"
          placeholder="请输入有效天数"
        ></el-input>
      </el-form-item>
      <el-form-item label="生效时间：" prop="validCreateDate" v-if="couponForm.validType == '2'">
        <el-date-picker
          v-model="couponForm.validCreateDate"
          type="date"
          value-format="yyyy-MM-dd"
          style="width:325px;"
          placeholder="请选择生效时间"
          :disabled="disabledFlag"
        ></el-date-picker>
      </el-form-item>
      <el-form-item label="失效时间：" prop="validEndDate" v-if="couponForm.validType == '2'">
        <el-date-picker
          v-model="couponForm.validEndDate"
          type="date"
          value-format="yyyy-MM-dd"
          style="width:325px;"
          placeholder="请选择失效时间"
          :disabled="disabledFlag"
        ></el-date-picker>
      </el-form-item>
      <el-form-item label="是否启用：">
        <el-radio-group v-model="couponForm.status" :disabled="disabledFlag">
          <el-radio-button label="1">是</el-radio-button>
          <el-radio-button label="0">否</el-radio-button>
        </el-radio-group>
      </el-form-item>
      <el-form-item label="使用说明：" prop="comments">
        <el-input
          type="textarea"
          v-model="couponForm.comments"
          :disabled="disabledFlag"
          placeholder="请输入卡券使用说明"
          maxlength="100"
          show-word-limit
          :autosize="{minRows:2}"
          style="width:650px;"
        ></el-input>
      </el-form-item>

      <el-form-item label="商品范围：">
        <el-radio-group v-model="couponForm.useScope" :disabled="disabledFlag">
          <el-radio-button label="0">通用</el-radio-button>
          <el-radio-button label="1">指定商品</el-radio-button>
        </el-radio-group>
      </el-form-item>
      <el-form-item label="适用商品：" prop="useScopeList" v-if="couponForm.useScope == '1'">
        <el-table
          :data="useScopeList"
          @selection-change="couponGoodsChecked"
          border
          v-if="couponForm.useScope == '1'"
          style="font-size: 10px;width:100%;"
          height="300"
          :header-cell-style="{background:'#eef1f6',color:'#606266'}"
        >
          <el-table-column type="selection" width="55" align="center"></el-table-column>
          <el-table-column prop="goodsName" label="商品名称" width="200" header-align="center"></el-table-column>
          <el-table-column prop="barCode" label="商品编码" width="180" header-align="center"></el-table-column>
          <el-table-column prop="goodsTypeName" label="商品分类" width="180" header-align="center"></el-table-column>
          <el-table-column prop="salePrice" label="商品价格" header-align="center" align="right"></el-table-column>
          <el-table-column prop="unitName" label="销售单位" header-align="center"></el-table-column>
        </el-table>
        <div style="margin-top:10px;">
          <el-button type="primary" @click="selectGoods()" v-if="!disabledFlag">选择商品</el-button>
          <el-button @click="deleteGoods('couponForm')" v-if="!disabledFlag">删除商品</el-button>
        </div>
      </el-form-item>

      <el-form-item label="店铺等级：">
        <el-radio-group v-model="couponForm.isStoreLevel" :disabled="disabledFlag">
          <el-radio-button label="0">通用</el-radio-button>
          <el-radio-button label="1">指定店铺等级</el-radio-button>
        </el-radio-group>
      </el-form-item>
      <el-form-item
        label="适用店铺等级："
        prop="couponShopLevelList"
        v-if="couponForm.isStoreLevel == '1'"
      >
        <el-table
          :data="couponShopLevelList"
          @selection-change="couponLevelChecked"
          border
          v-if="couponForm.isStoreLevel == '1'"
          style="font-size: 10px;width:70%;"
          height="300"
          :header-cell-style="{background:'#eef1f6',color:'#606266'}"
        >
          <el-table-column type="selection" width="55" align="center"></el-table-column>
          <el-table-column prop="gradelevelName" label="等级名称" width="200" header-align="center"></el-table-column>
          <el-table-column prop="levelNumber" label="等级序号" width="120" align="center"></el-table-column>
          <el-table-column prop="beginScore" label="分值范围" header-align="center">
            <template slot-scope="scope">{{scope.row.beginScore}}至{{scope.row.endScore}}</template>
          </el-table-column>
        </el-table>
        <div style="margin-top:10px;">
          <el-button type="primary" @click="selectLevel('couponForm')" v-if="!disabledFlag">选择店铺等级</el-button>
          <el-button @click="deleteLevel('couponForm')" v-if="!disabledFlag">删除店铺等级</el-button>
        </div>
      </el-form-item>

      <el-form-item>
        <el-button type="primary" @click="submitForm('couponForm')" v-if="!disabledFlag">保 存</el-button>
        <el-button @click="resetForm('couponForm')">取 消</el-button>
      </el-form-item>
    </el-form>

    <el-dialog title="选择商品" :visible.sync="dialogVisibleGood" width="65%">
      <el-form
        :inline="true"
        :model="formInline"
        class="search-form-inline"
        style="margin-top:-20px;"
      >
        商品名称/编码：
        <el-input v-model="formInline.goodsName" style="width:200px;" placeholder="商品名称/编码"></el-input>&nbsp;&nbsp;
        商品分类：
        <el-select v-model="formInline.goodsType">
          <el-option value>全部</el-option>
          <el-option
            v-for="item in goodsTypeList"
            :key="item.goodsTypeId"
            :label="item.goodsTypeName"
            :value="item.goodsTypeId"
          ></el-option>
        </el-select>
        <el-button type="primary" size="mini" icon="el-icon-search" @click="getGoodsList()">查询</el-button>
      </el-form>
      <el-table
        :data="goodsList"
        @selection-change="goodsChecked"
        border
        style="font-size: 10px;width:100%;"
        height="300"
        :header-cell-style="{background:'#eef1f6',color:'#606266'}"
      >
        <el-table-column type="selection" width="55" align="center"></el-table-column>
        <el-table-column prop="goodsName" label="商品名称" width="200" header-align="center"></el-table-column>
        <el-table-column prop="barCode" label="商品编码" width="180" header-align="center"></el-table-column>
        <el-table-column prop="goodsTypeName" label="商品分类" width="180" header-align="center"></el-table-column>
        <el-table-column prop="salePrice" label="商品价格" header-align="center" align="right"></el-table-column>
        <el-table-column prop="unitName" label="销售单位" header-align="center"></el-table-column>
      </el-table>
      <div class="block" style="margin-top:5px;">
        <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :page-sizes="[10, 20, 30, 50, 100]"
          :current-page="listQuery.current"
          :page-size="listQuery.size"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
        ></el-pagination>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisibleGood = false">取 消</el-button>
        <el-button type="primary" @click="selectConfirm()">确 定</el-button>
      </span>
    </el-dialog>

    <el-dialog title="选择店铺等级" :visible.sync="dialogVisibleLevel" width="50%">
      <el-table
        :data="shopLevelList"
        @selection-change="levelChecked"
        border
        style="font-size: 10px;width:100%;margin-top:-20px;"
        height="300"
        :header-cell-style="{background:'#eef1f6',color:'#606266'}"
      >
        <el-table-column type="selection" width="55" align="center"></el-table-column>
        <el-table-column prop="gradelevelName" label="等级名称" width="200" header-align="center"></el-table-column>
        <el-table-column prop="levelNumber" label="等级序号" width="120" align="center"></el-table-column>
        <el-table-column prop="beginScore" label="分值范围" header-align="center">
          <template slot-scope="scope">{{scope.row.beginScore}}至{{scope.row.endScore}}</template>
        </el-table-column>
      </el-table>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisibleLevel = false">取 消</el-button>
        <el-button type="primary" @click="levelConfirm()">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>
<script>
import {
  queryStoreGradelevelLule,
  queryCouponById,
  createCoupon,
  updateCoupon
} from "@/api/promotionProgramEdit";

import { getGoodsTypeList, querygoodsByName } from "@/api/product";

export default {
  data() {
    return {
      loading: true,
      couponShopLevelList: [],
      shopLevelList: [],
      lsLevelList: [],
      lsCouponLevelList: [],
      goodsTypeList: [],
      useScopeList: [],
      goodsList: [],
      lsCouponGoodsList: [],
      lsGoodsList: [],
      arrid: [],
      couponForm: {
        uuid: "",
        couponName: "",
        couponType: "",
        validType: "",
        validDate: "",
        validCreateDate: "",
        validEndDate: "",
        conponLimitMoney: "",
        couponMoney: "",
        couponDiscount: "",
        useScope: "",
        isStoreLevel: "",
        comments: "",
        status: "",
        couponPicture: "",
        store: [],
        goods: []
      },
      formInline: {
        goodsName: "",
        goodsType: ""
      },
      dialogVisibleGood: false,
      dialogVisibleLevel: false,
      disabledFlag: false,
      listQuery: {
        current: 1,
        size: 10
      },
      total: 0,
      rules: {
        // couponName: [{ required: true, message: "请输入卡券名称", trigger: "blur" }]
      }
    };
  },
  mounted() {
    var v = this.$route.params.edit;
    if (v) {
      // 修改，回显值
      this.couponForm.uuid = v.uuid;
      this.couponForm.couponName = v.couponName;
      this.couponForm.couponType = v.couponType;
      this.couponForm.validType = v.validType;
      this.couponForm.validDate = v.validDate;
      this.couponForm.validCreateDate = v.validCreateDate;
      this.couponForm.validEndDate = v.validEndDate;
      this.couponForm.conponLimitMoney = v.conponLimitMoney;
      this.couponForm.couponMoney = v.couponMoney;
      this.couponForm.couponDiscount = v.couponDiscount;
      this.couponForm.useScope = v.useScope;
      this.couponForm.isStoreLevel = v.isStoreLevel;
      this.couponForm.comments = v.comments;
      this.couponForm.status = v.status;
      this.couponForm.couponPicture = v.couponPicture;

      this.getCouponById(v.uuid);

      if (v.used == '1') {
        this.disabledFlag = true;
      }
    } else {
      // 新增，默认值
      this.couponForm.uuid = "";
      this.couponForm.couponType = "1";
      this.couponForm.validType = "1";
      this.couponForm.useScope = "0";
      this.couponForm.isStoreLevel = "0";
      this.couponForm.status = "1";
      this.couponForm.couponPicture = "3";
      this.getGoodsTypeList();
      this.getGoodsList();
      this.getShopLevelList();
    }
  },
  methods: {
    goback() {
      this.$router.go("-1");
    },
    numberBlur(e, name) {
      if (e.target.value == "") {
        return;
      }
      let flag = new RegExp("^[1-9][0-9]*$").test(e.target.value);
      if (!flag) {
        this.$message({
          message: name + "请输入正整数",
          type: "warning"
        });
        e.target.value = "";
      }
    },
    discountBlur(e, name) {
      if (e.target.value == "") {
        return;
      }
      let zz = new RegExp("^[0]+(.[0-9]{1,2})?$");
      if (
        !zz.test(e.target.value) ||
        e.target.value <= 0 ||
        e.target.value >= 1
      ) {
        this.$message({
          message: name + "请输入0-1以内的小数",
          type: "warning"
        });
        e.target.value = "";
      }
    },
    getCouponById(uuid) {
      queryCouponById(uuid).then(res => {
        if (
          res.result.memberGoodsInfoDTOS != null &&
          res.result.memberGoodsInfoDTOS.length > 0
        ) {
          this.useScopeList = res.result.memberGoodsInfoDTOS;
        }
        if (
          res.result.storeGradelevelRuleDTOS != null &&
          res.result.storeGradelevelRuleDTOS.length > 0
        ) {
          this.couponShopLevelList = res.result.storeGradelevelRuleDTOS;
        }
        this.getGoodsTypeList();
        this.getGoodsList();
        this.getShopLevelList();
      });
      this.loading = false;
    },
    getGoodsTypeList() {
      getGoodsTypeList().then(res => {
        this.goodsTypeList = res.records;
      });
      this.loading = false;
    },
    getGoodsList() {
      let data = {
        size: this.listQuery.size,
        current: this.listQuery.current,
        condition: {
          goodsName: this.formInline.goodsName,
          goodsTypeId: this.formInline.goodsType
        },
        ascs: [],
        descs: []
      };
      querygoodsByName(data).then(res => {
        this.goodsList = res.records;
        this.total = res.total;
        // 去掉已选的
        for (var i in this.useScopeList) {
          this.removeByValue(this.goodsList, "uuid", this.useScopeList[i].uuid);
          this.total -= 1;
          this.total = this.total < 0 ? 0 : this.total;
        }
      });
      this.loading = false;
    },
    getShopLevelList() {
      let data = {
        size: 200,
        current: 1,
        condition: {},
        ascs: [],
        descs: []
      };
      queryStoreGradelevelLule(data).then(res => {
        this.shopLevelList = res.records;
        // 去掉已选的
        for (var i in this.couponShopLevelList) {
          this.removeByValue(
            this.shopLevelList,
            "uuid",
            this.couponShopLevelList[i].uuid
          );
        }
      });
      this.loading = false;
    },

    couponGoodsChecked(row) {
      this.lsCouponGoodsList = row;
    },
    goodsChecked(row) {
      this.lsGoodsList = row;
    },
    selectConfirm() {
      // 保存已选择的商品
      this.dialogVisibleGood = !this.dialogVisibleGood;
      this.useScopeList = this.useScopeList.concat(this.lsGoodsList);
      for (var i in this.lsGoodsList) {
        this.removeByValue(this.goodsList, "uuid", this.lsGoodsList[i].uuid);
      }
    },
    selectGoods() {
      // 显示选择商品对话框
      this.dialogVisibleGood = !this.dialogVisibleGood;
    },
    deleteGoods() {
      // 删除已选择的商品
      this.goodsList = this.goodsList.concat(this.lsCouponGoodsList);
      for (var i in this.lsCouponGoodsList) {
        this.removeByValue(
          this.useScopeList,
          "uuid",
          this.lsCouponGoodsList[i].uuid
        );
      }
    },

    couponLevelChecked(row) {
      this.lsCouponLevelList = row;
    },
    levelChecked(row) {
      this.lsLevelList = row;
    },
    levelConfirm() {
      // 保存已选择的店铺等级
      this.dialogVisibleLevel = !this.dialogVisibleLevel;
      this.couponShopLevelList = this.couponShopLevelList.concat(
        this.lsLevelList
      );
      for (var i in this.lsLevelList) {
        this.removeByValue(
          this.shopLevelList,
          "uuid",
          this.lsLevelList[i].uuid
        );
      }
    },
    selectLevel() {
      // 显示选择店铺等级对话框
      this.dialogVisibleLevel = !this.dialogVisibleLevel;
    },
    deleteLevel() {
      // 删除已选择的店铺等级
      this.shopLevelList = this.shopLevelList.concat(this.lsCouponLevelList);
      for (var i in this.lsCouponLevelList) {
        this.removeByValue(
          this.couponShopLevelList,
          "uuid",
          this.lsCouponLevelList[i].uuid
        );
      }
    },

    submitForm(formName) {
      if (
        this.couponForm.couponName == "" ||
        this.couponForm.couponName == null
      ) {
        this.$message.error("请输入卡券名称");
        return;
      }
      if (
        this.couponForm.conponLimitMoney == "" ||
        this.couponForm.conponLimitMoney == null
      ) {
        this.$message.error("请输入卡券使用条件");
        return;
      }
      if (this.couponForm.couponType == "3") {
        if (
          this.couponForm.couponDiscount == "" ||
          this.couponForm.couponDiscount == null
        ) {
          this.$message.error("请输入卡券折扣");
          return;
        }
      } else {
        if (
          this.couponForm.couponMoney == "" ||
          this.couponForm.couponMoney == null
        ) {
          this.$message.error("请输入卡券面值");
          return;
        }
        if (this.couponForm.conponLimitMoney <= this.couponForm.couponMoney) {
          this.$message.error("卡券使用条件需大于卡券面值，请重新输入");
          return;
        }
      }
      if (this.couponForm.validType == "1") {
        if (
          this.couponForm.validDate == "" ||
          this.couponForm.validDate == null
        ) {
          this.$message.error("请输入有效天数");
          return;
        }
      } else {
        if (
          this.couponForm.validCreateDate == "" ||
          this.couponForm.validCreateDate == null
        ) {
          this.$message.error("请输入生效时间");
          return;
        }
        if (
          this.couponForm.validEndDate == "" ||
          this.couponForm.validEndDate == null
        ) {
          this.$message.error("请输入失效时间");
          return;
        }
        if (this.couponForm.validCreateDate > this.couponForm.validEndDate) {
          this.$message.error("失效时间不能早于生效时间");
          return;
        }
      }
      if (
        this.couponForm.useScope == "1" &&
        (this.useScopeList == null || this.useScopeList.length == 0)
      ) {
        this.$message.error("请选择商品范围");
        return;
      }
      if (
        this.couponForm.isStoreLevel == "1" &&
        (this.couponShopLevelList == null ||
          this.couponShopLevelList.length == 0)
      ) {
        this.$message.error("请选择店铺等级");
        return;
      }
      for (var i in this.couponShopLevelList) {
        this.couponShopLevelList[i].storeLevelId = this.couponShopLevelList[
          i
        ].uuid;
        delete this.couponShopLevelList[i].createTime;
        delete this.couponShopLevelList[i].updateTime;
      }
      for (var i in this.useScopeList) {
        this.useScopeList[i].goodsId = this.useScopeList[i].uuid;
        delete this.useScopeList[i].createTime;
        delete this.useScopeList[i].updateTime;
      }
      this.couponForm.store = this.couponShopLevelList;
      this.couponForm.goods = this.useScopeList;
      // console.log(this.couponForm);
      if (this.couponForm.uuid == "") {
        // 新增卡券
        createCoupon(this.couponForm).then(res => {
          if (res.code == "1") {
            this.$message({
              showClose: true,
              message: "保存成功",
              type: "success"
            });
            this.$router.push("couponList");
          } else {
            this.$message.error("保存失败");
          }
        });
      } else {
        // 修改卡券
        updateCoupon(this.couponForm).then(res => {
          if (res.code == "1") {
            this.$message({
              showClose: true,
              message: "保存成功",
              type: "success"
            });
            this.$router.push("couponList");
          } else {
            this.$message({
              showClose: true,
              message: "保存失败",
              type: "success"
            });
          }
        });
      }
    },
    resetForm(formName) {
      // this.$refs[formName].resetFields();
      this.$router.push("couponList");
    },
    handleSizeChange(val) {
      this.listQuery.size = val;
      this.getGoodsList();
    },
    handleCurrentChange(val) {
      this.listQuery.current = val;
      this.getGoodsList();
    },
    // 数组，属性，属性值
    removeByValue: function(arr, attr, value) {
      if (arr == null) {
        return;
      }
      var index = 0;
      for (var i in arr) {
        if (arr[i][attr] == value) {
          index = i;
          break;
        }
      }
      arr.splice(index, 1);
    }
  }
};
</script>>
<style lang="less" scoped>
.el-col-20 {
  border: 1px solid #ebeef5;
  margin-left: 150px;
  width: 60%;
}
.el-input {
  width: 60%;
}
.search-form-inline {
  border: 1px solid #ebeef5;
  line-height: 30px;
  padding: 12px;
  margin-bottom: 5px;
}
</style>